﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperKit
{
    class UnzipAll : CommandExecutor {
        public static string ZipExe => ConfigReader.Instance.GetString("7ZPath");
        public const string UNZIP_DIR = "(_UNZIP)";
        public List<FileInfo> Files { get; private set; }
        private SimpleThreadExecutor<FileInfo> Executor { get; set; }
        public List<string> passwords;
        private int thread { get; }
        private FileContainer container { get; }


        public UnzipAll(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
            thread = arg.GetInteger("-thread", 1);
            GaindPasswords(arg);
            container = new FileContainer(UNZIP_DIR, new DirectoryInfo(FilePath), arg.TargetDir);

        }

        public override void Execute() {
            base.Execute();
            Files = Kit.GetAllFiles(null, new DirectoryInfo(FilePath), Kit.ZIP_EXTS);
            Executor = new SimpleThreadExecutor<FileInfo>(Files, thread);
            Executor.Start(OnProcess, End);
        }

        private void OnProcess(FileInfo item) {
            string path = container.GetDir(item);
            string arg;
            if (passwords.Count > 0) {
                foreach (var pwd in passwords) {
                    arg = string.Format("x -y \"{0}\" -p{2} -o\"{1}\"", item.FullName, path, pwd);
                    ExecuteZip(arg);
                }
            } else {
                arg = string.Format("x -y \"{0}\" -o\"{1}\"", item.FullName, path);
                ExecuteZip(arg);
            }
            SetStatus($"{Executor.GetProcessString()} {item.Name}");
        }


        private void GaindPasswords(ArgReader arg) {
            passwords = new List<string>();
            var pwd = arg.GetParameter("-pwd");

            // pwds包括多个密码，其中用“|”分隔，这里有一个BUG，如果密码中拥有“|”，那么会出问题。但暂时就这样吧。
            if (Kit.IsEmpty(pwd) == false) {
                var splits = pwd.Split('|');
                foreach (var i in splits) {
                    passwords.Add(i);
                }
            }
        }



        public static string ExecuteZip(string cmd) {
            Process p = new Process();
            //设置要启动的应用程序
            p.StartInfo.FileName = ZipExe;
            p.StartInfo.Arguments = cmd;
            //是否使用操作系统shell启动
            p.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            //p.StartInfo.RedirectStandardInput = true;
            //输出信息
            //p.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            //p.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p.StartInfo.CreateNoWindow = true;
            //启动程序
            p.Start();

            //等待程序执行完退出进程
            p.WaitForExit();
            p.Close();

            return Kit.EMPTY;
        }

    }
}
